//
//  JJzixunViewController.m
//  JJHW_coreData
// 资讯首页
//  Created by lizhenqiang on 16/4/9.
//  Copyright © 2016年 HFKJ_LZQ. All rights reserved.
//

#import "JJzixunViewController.h"
#import "CityObj.h"
#import "SelectCityViewController.h"
#import "NewsFirstRecImageCell.h"
#import "NewsBigImageCell.h"
#import "NewsNoImageCell.h"
#import "NewsSmallImageCell.h"
#import "NewsRecoImageObj.h"
#import "NewsListObj.h"
#import "SearchViewController.h"

#import "ZiXunDetailViewController.h"
#import "ZiXunBottomView.h"
#import "ZXbottomView.h"
#import "SplashObj.h"
#import <CoreLocation/CoreLocation.h>
#import "StartPageHandle.h"//启动页处理
#import "HZUIViewForGuide.h"
#import "StartPageViewController.h"
#define NAVBAR_CHANGE_POINT 64
#define KcaidanInfo @"caiDanData"

@interface JJzixunViewController ()<UIScrollViewDelegate,CLLocationManagerDelegate,HZViewForGuideDataSource>
{
    CGFloat alpha;
    CLLocationManager *_locationManager;
    CLGeocoder *_geocoder;
}

@property(strong, nonatomic)CityObj *cityObj;//选择的城市
@property(strong, nonatomic)UIButton *rightBtn;
@property(strong, nonatomic)UILabel *rightLabel;//显示城市
@property(assign, nonatomic)BOOL isHadBannar;//是否有广告 来控制navBar状态
@property(strong, nonatomic)NSMutableArray *bannarArray;
@property(strong, nonatomic)NSMutableArray *splashArray;//菜单数组
@property(strong, nonatomic)NSMutableArray *caiDanInfoArray;
@property(strong, nonatomic)ZiXunBottomView *bottomView;
//@property(strong, nonatomic)ZXbottomView *bottomView;
@end

@implementation JJzixunViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}

- (void)loadGuideView:(UIView *)view
{
    //    NSString *FirstUsedApp =[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if (![[NSUserDefaults standardUserDefaults] boolForKey:kVersion])
    {
        StartPageViewController *start = [[StartPageViewController alloc] init];
        self.view.window.rootViewController = start;
        [CDKeyWindow setRootViewController:start];
//        HZUIViewForGuide *hzviewForGuide =[[HZUIViewForGuide alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)];
//        hzviewForGuide.tag = 3001;
//        hzviewForGuide.superflag = @"YINDAO";
//        hzviewForGuide.numofpages = 4;
//        hzviewForGuide.dataSource =self;
//        [hzviewForGuide initSubviews:self.view.window];
    }
    
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
//    StartPageHandle *start = [[StartPageHandle alloc] init];
//    [start loadGuideView:self.view];
    [self loadGuideView:self.view];
    // Do any additional setup after loading the view.
    _cityObj = [[CityObj alloc] init];
    _cityObj.name = @"日本";
    _isHadBannar = YES;
    _bannarArray = [[NSMutableArray alloc] init];
    _splashArray = [NSMutableArray new];
    [self addLabelNoDataToView:self.tableView AndText:@"暂无数据" andFrame:kNoDataLabelFrame];
    NSUserDefaults *mydefault = [NSUserDefaults standardUserDefaults];
    NSString *caidan = [mydefault objectForKey:KcaidanInfo];
    if (![NSString isEmpty:caidan]) {
        _caiDanInfoArray = [NSJSONSerialization returnObjectWithJsonStr:caidan];
    }
    for (NSDictionary *dic in _caiDanInfoArray) {
        SplashObj *obj = [[SplashObj alloc] initWithDictionary:dic];
        [_splashArray addObject:obj];
    }
    
//     NSString *filePath = [[NSString getFilePath:@"caidan"] stringByAppendingPathComponent:@"caidan.plist"];
//    NSFileManager *fm = [[NSFileManager alloc] init];
//    if ([fm fileExistsAtPath:filePath]) {
//        NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
//        for (NSDictionary *dic in array) {
//            SplashObj *obj = [[SplashObj alloc] initWithDictionary:dic];
//            [_splashArray addObject:obj];
//        }
//    }
//    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
//    for (NSDictionary *dic in array) {
//        SplashObj *obj = [[SplashObj alloc] initWithDictionary:dic];
//        [_splashArray addObject:obj];
//    }
    
    
    [self.view addSubview:self.tableView];
    [self addRefreshHeaderAndFooterView:self.tableView];
    _bottomView = [[ZiXunBottomView alloc] initWithFrame:CGRectMake(0, DeviceHeight-49, DeviceWidth, 49)];
    _bottomView.VC = self;
    [_bottomView setViewData:_splashArray];
    _bottomView.block = ^(ZXbottomRequestType type,SplashObj *obj){
    //点击不同的按钮 去做不同的请求
    };
    _bottomView.VC = self;
    [self.view addSubview:_bottomView];
//    _bottomView = [[ZXbottomView alloc] initWithFrame:CGRectMake(0, 0, DeviceHeight-49, 49)];
//    [_bottomView setViewData:_splashArray andTitle:nil];
    if (_isHadBannar) {
        self.tableView.frame = CGRectMake(0, 0, DeviceWidth, DeviceHeight-49);
    }
    else
    {
        self.tableView.frame = CGRectMake(0, 64, DeviceWidth, DeviceHeight-49);
    }

    [self setNavBar_rightItem];
    [self caidanListRequest];//获取菜单 鲸美食  鲸快播
//    [self defaultCountryRequest];//获取默认国家 现在默认 日本countryid
//    [self getRecoImageReqeust];
//    [self.tableView registerNib:[UINib nibWithNibName:@"NewsFirstRecImageCell" bundle:nil] forCellReuseIdentifier:@"NewsFirstRecImageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsBigImageCell" bundle:nil]  forCellReuseIdentifier:@"NewsBigImageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsNoImageCell" bundle:nil]  forCellReuseIdentifier:@"NewsNoImageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsSmallImageCell" bundle:nil] forCellReuseIdentifier:@"NewsSmallImageCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsFirstRecImageCell" bundle:nil] forCellReuseIdentifier:@"NewsFirstRecImageCell"];//
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    self.tableView.estimatedRowHeight = 140;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    _geocoder=[[CLGeocoder alloc]init];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [_locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
    }
    
}
-(void)setNavBarTitleView
{
   
//
//    self.navLabel = [[UITextField alloc] initWithFrame:CGRectMake(30, 0, DeviceWidth-90, 30)];
//    
//    self.backImageview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 15, 15)];
//    self.backImageview.image = [UIImage imageNamed:@"icon_searchsmall"];
//    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 7, DeviceWidth-70, 30)];
    NavBarItem *item = [[NavBarItem alloc] init];
    item.type = NavBarItemTypeOnlyStr;
    [self setLeftNavItemWith:item];
    self.titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 7, DeviceWidth-90, 30)];//100
    self.navLabel = [[UITextField alloc] initWithFrame:CGRectMake(30, 1, DeviceWidth-145, 28)];//145
    self.navLabel.enabled = NO;
     self.navLabel.font = themeFont15;
    self.backImageview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 15, 15)];
    self.backImageview.image = [UIImage imageNamed:@"icon_searchsmall"];
    [self.titleView addSubview:self.navLabel];
    [self.titleView addSubview:self.backImageview];
    self.titleView.layer.cornerRadius = 15.0f;
    self.titleView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoSearch)];
    singTap.numberOfTapsRequired = 1;
    [self.titleView addGestureRecognizer:singTap];
    self.navigationItem.titleView = self.titleView;
    
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 7, DeviceWidth-100, 30)];
//    titleView.backgroundColor = [UIColor redColor];
//    self.navigationItem.titleView = titleView;
    
}

//-(void)setNavBarTitleView
//{//设置titleview
//    self.navLabel = [[UITextField alloc] initWithFrame:CGRectMake(30, 0, DeviceWidth-180, 30)];
//   
//    self.backImageview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 15, 15)];
//    self.backImageview.image = [UIImage imageNamed:@"icon_searchsmall"];
//    self.titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 7, DeviceWidth-150, 30)];//(70, 0, DeviceWidth-130, 30)
//    //    _clearBtn.frame = CGRectMake(titleView.frame.size.width-33, 0, 30, 30);
////    [_titleView addSubview:_backImageview];
////    [_titleView addSubview:_navLabel];
////    //    [titleView addSubview:_clearBtn];
////    _titleView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.4];
////    _titleView.layer.borderColor = kDefaultWhiteColor.CGColor;
////    _titleView.layer.borderWidth = 1.0;
////    //    titleView.alpha = 0.6;
////    _titleView.layer.cornerRadius = 15.0f;
////    _titleView.layer.masksToBounds = YES;
////    //    [titleView addSubview:titleImageView];
////    self.navigationItem.titleView =_titleView;
////    _titleView.userInteractionEnabled = YES;
////    UITapGestureRecognizer *singTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoSearch)];
////    singTap.numberOfTapsRequired = 1;
////    [_titleView addGestureRecognizer:singTap];
////    self.navigationItem.titleView = _titleView;
//    
//}

#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
    
    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
}


#pragma mark 根据地名确定地理坐标
-(void)getCoordinateByAddress:(NSString *)address{
    //地理编码
    [_geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        //取得第一个地标，地标中存储了详细的地址信息，注意：一个地名可能搜索出多个地址
        CLPlacemark *placemark=[placemarks firstObject];
        
        CLLocation *location=placemark.location;//位置
        CLRegion *region=placemark.region;//区域
        NSDictionary *addressDic= placemark.addressDictionary;//详细地址信息字典,包含以下部分信息
        //        NSString *name=placemark.name;//地名
        //        NSString *thoroughfare=placemark.thoroughfare;//街道
        //        NSString *subThoroughfare=placemark.subThoroughfare; //街道相关信息，例如门牌等
        //        NSString *locality=placemark.locality; // 城市
        //        NSString *subLocality=placemark.subLocality; // 城市相关信息，例如标志性建筑
        //        NSString *administrativeArea=placemark.administrativeArea; // 州
        //        NSString *subAdministrativeArea=placemark.subAdministrativeArea; //其他行政区域信息
        //        NSString *postalCode=placemark.postalCode; //邮编
        //        NSString *ISOcountryCode=placemark.ISOcountryCode; //国家编码
        //        NSString *country=placemark.country; //国家
        //        NSString *inlandWater=placemark.inlandWater; //水源、湖泊
        //        NSString *ocean=placemark.ocean; // 海洋
        //        NSArray *areasOfInterest=placemark.areasOfInterest; //关联的或利益相关的地标
        NSLog(@"位置:%@,区域:%@,详细信息:%@",location,region,addressDic);
    }];
}

#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [_geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        NSLog(@"详细信息:%@",placemark.addressDictionary);
        NSLog(@"具体地址名称为%@",placemark.name);
    }];
}



-(void)loadDataWithCurrentpage:(NSInteger)currentpage
{
//    if (![NSString isEmpty: _cityObj.countryId]) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.currentPage = currentpage;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        if (currentpage==0) {
            if ([NSString isEmpty:_cityObj.countryId]) {
                
                [self defaultCountryRequest];//获取默认国家 现在默认 日本countryid
            }
            [self getRecoImageReqeust];
        }
        [self getNewsListRequest];
//    }
}

-(void)gotoSearch
{
    CDLog(@"进入搜索页面");
    
    SearchViewController *search = [[SearchViewController alloc] init];
//    SearchViewController *search = (SearchViewController *)[self getVCfromStoryboard:@"Common" andVCname:@"SearchViewController"];
    
    [self.navigationController pushViewController:search animated:YES];
}

-(void)defaultCountryRequest
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    [[CDAPIManager sharedManager] request_getDefaultCountry_withParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        //这个接口调用成功了
        /*
         {
         data =     {
         id = 5713ae48c4906d1c328b4569;
         name = "\U65e5\U672c";
         };
         msg = "";
         status = 0;
         }
         */
        if (isSuccess) {
            
            NSDictionary *dic = [data objectForKey:@"data"];
            _cityObj.name = [dic objectForKey:@"name"];
            _cityObj.countryId = [dic objectForKey:@"id"];
            [Person sharePerson].countryId = [dic objectForKey:@"id"];
            if ([NSString isEmpty:_cityObj.countryId]) {
                _cityObj.countryId = KdefaultCountryId;
                [Person sharePerson].countryId = KdefaultCountryId;//日本的id
            }
            [self setNavBar_rightItem];
            [self loadDataWithCurrentpage:0];
        }
        else
        {
            _cityObj.name = @"日本";
            _cityObj.countryId = KdefaultCountryId;//日本的id
            [Person sharePerson].countryId = KdefaultCountryId;//日本的id
            [self setNavBar_rightItem];
//            [self loadDataWithCurrentpage:0];
        }
        
    }];
}
-(void)caidanListRequest
{//请求菜单标签接口
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    
    [[CDAPIManager sharedManager] request_splash_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        //这个接口调用成功了
        //需要把这部分数据给保存一下
//        NSString *filePath = [[NSString getFilePath:@"caidan"] stringByAppendingPathComponent:@"caidan.plist"];
//        NSString *st = [NSJSONSerialization returnJsonStrWithObject:data];
//        NSDictionary *mydic = [NSJSONSerialization returnObjectWithJsonStr:st];
        if (isSuccess) {
            
            NSArray *array = [data objectForKey:@"data"];
            if (![array isEqualToArray:_caiDanInfoArray]) {
                
                NSUserDefaults *mydefault = [NSUserDefaults standardUserDefaults];
                NSString *st = [NSJSONSerialization returnJsonStrWithObject:array];
                [mydefault setObject:st forKey:KcaidanInfo];
                [mydefault synchronize];
                [_splashArray removeAllObjects];
                for (NSDictionary *dic in array) {
                    SplashObj *obj = [[SplashObj alloc] initWithDictionary:dic];
                    [_splashArray addObject:obj];
                }
                
                [_bottomView setViewData:_splashArray];
            }
        }
        else
        {
            
        }
        
    }];
    
}
-(void)getRecoImageReqeust
{//广告
    NSString *cityId = [NSString isEmpty:_cityObj.internalBaseClassIdentifier]?@"":_cityObj.internalBaseClassIdentifier;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:_cityObj.countryId,@"countryId",cityId,@"districtId",@"",@"pCategoryId",@"",@"categoryId", nil];
    //request_cityImage_WithParams
    [[CDAPIManager sharedManager] request_cityImage_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        //根据他来看 是否显示 有推荐图的cell
        if (isSuccess) {
            NSArray *array = [data objectForKey:@"data"];
            [_bannarArray removeAllObjects];
            if (array.count>0) {
                _isHadBannar = YES;
                for (NSDictionary *dic in array) {
                    NewsRecoImageObj *obj = [[NewsRecoImageObj alloc] initWithDictionary:dic];
                    [_bannarArray addObject:obj];
                }
            }
            else
            {
                _isHadBannar = NO;
            }
            [self isHadBannarHandle:_isHadBannar];
//            [self.tableView reloadData];
        }
        else
        {
            _isHadBannar = NO;
            [_bannarArray removeAllObjects];
            [self isHadBannarHandle:_isHadBannar];
            //请求失败做相应的处理
        }
        [self.tableView reloadData];
    }];
}
-(void)isHadBannarHandle:(BOOL)flag
{
    if (flag) {
        self.tableView.frame = CGRectMake(0, 0, DeviceWidth, DeviceHeight-49);
    }
    else
    {
        self.tableView.frame = CGRectMake(0, 64, DeviceWidth, DeviceHeight-49-64);
    }
    [self scrollViewDidScroll:self.tableView];
    [self.tableView reloadData];
}
-(void)getNewsListRequest
{//资讯列表
/*
count:20,一次请求多少条记录
offset:1,从第几条记录开始请求,偏移量
pCategoryId:xxx,一级分类id
categoryId:xxx二级分类id
countryId:xxx国家id
districtId:xxx城市id
 */
    NSInteger offset = self.currentPage * kPageSize;
    NSInteger count = kPageSize;
    NSString *cityId = [NSString isEmpty:_cityObj.internalBaseClassIdentifier]?@"":_cityObj.internalBaseClassIdentifier;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:NSStringFromIntL(count),@"count",NSStringFromIntL(offset),@"offset",@"",@"pCategoryId",@"",@"categoryId",_cityObj.countryId,@"countryId",cityId,@"districtId", nil];
    
    [[CDAPIManager sharedManager] request_newsList_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            
            NSDictionary *mydic = [data objectForKey:@"data"];
            NSArray *array = [mydic objectForKey:@"list"];
            if (array.count>0) {
                if (self.currentPage == 0) {
                    [self.pageDataArr removeAllObjects];
                }
            }
            for (NSDictionary *dic in array) {
                NewsListObj *obj = [[NewsListObj alloc] initWithDictionary:dic];
                [self.pageDataArr addObject:obj];
                
            }
            NSInteger total = [[mydic objectForKey:@"total"] integerValue];
            NSInteger totalPage;
            if (total % kPageSize == 0) {
                totalPage = total/kPageSize;
            }
            else
            {
                totalPage = total/kPageSize + 1;
            }
            self.labelNoData.hidden = (self.pageDataArr.count<1&&_bannarArray.count<1)?NO:YES;
            [self setTotalPages:totalPage-1];
            [self.tableView reloadData];
            
        }
        else
        {
            self.labelNoData.hidden = (self.pageDataArr.count<1&&_bannarArray.count<1)?NO:YES;
        }
        [self endRefreshControlLoading];
    }];
}

//-(void)setNavTitleView
//{
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth-170, 30)];
//    
//    self.navigationItem.titleView = view;
//}
-(void)setNavBar_rightItem
{
    //一个view add 一个label 和一个 button  的item 有点击事件
    
    CGFloat width = [NSString calculateTextWidth:22 Content:_cityObj.name font:themeFont17];//这个是title的长度
    //图片的尺寸是 14*14
    CGFloat height = 30;
    CGRect viewFrame = CGRectMake(DeviceWidth-width, 0, width+16, height);//+16
    CGFloat totalWidth = CGRectGetWidth(viewFrame);
    UIView *view = [[UIView alloc] initWithFrame:viewFrame];
    _rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, width, height)];
    _rightLabel.text = _cityObj.name;
    _rightLabel.font = themeFont17;
    _rightLabel.textColor = kDefaultWhiteColor;
    _rightLabel.textAlignment = NSTextAlignmentRight;//
    _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(totalWidth-8, (height-14)/2+2, 14, 14)];//
    UIImage *image = [UIImage imageNamed:@"icon_skip"];
    [_rightBtn setImage:image forState:UIControlStateNormal];
    [_rightBtn setImage:image forState:UIControlStateSelected];
    [_rightBtn setImage:image forState:UIControlStateHighlighted];
    [_rightBtn addTarget:self action:@selector(selectCity) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_rightLabel];
    [view addSubview:_rightBtn];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    view.userInteractionEnabled = YES;
    UITapGestureRecognizer *singTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCity)];
    singTap.numberOfTapsRequired = 1;
    [view addGestureRecognizer:singTap];
    self.navigationItem.rightBarButtonItem = rightItem;
}

-(void)selectCity
{
//    SelectCityViewController *city = (SelectCityViewController *)[self getVCfromStoryboard:@"Common" andVCname:@"SelectCityViewController"];
//    SelectCityViewController *city = [[SelectCityViewController alloc] init];
    UIStoryboard *storyBorad = [UIStoryboard storyboardWithName:@"Common" bundle:nil];
    SelectCityViewController *city = [storyBorad instantiateViewControllerWithIdentifier:@"SelectCityViewController"];
    city.titleForNav = @"城市选择";
    city.countrId = _cityObj.countryId;
    city.block = ^(CityObj *obj){
        _cityObj = obj;
        [Person sharePerson].countryId = obj.countryId;//
        [Person sharePerson].cityId = obj.internalBaseClassIdentifier;
         [self setNavBar_rightItem];
        [self loadDataWithCurrentpage:0];
    };
    [self.navigationController pushViewController:city animated:YES];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if (_isHadBannar) {
        
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        [self scrollViewDidScroll:self.tableView];
//        UIColor *color = NavBarBJColor;
//        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:0.0]];
    }
    else
    {
//        UIColor *color = NavBarBJColor;
//        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:1.0]];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    if (_isHadBannar) {
////        [self.navigationController.navigationBar lt_reset];
//        UIColor *color = NavBarBJColor;
//        [self scrollViewDidScroll:self.tableView];
//        [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:1.0]];
//    }
//    
//    
////    topBarView.hidden = YES;
    UIColor * color = NavBarBJColor;
    alpha = 1;
    [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:alpha]];
    self.titleView.backgroundColor = [UIColor whiteColor];
    self.backImageview.image = [UIImage imageNamed:@"icon_search_gray"];
    self.navLabel.backgroundColor = [UIColor whiteColor];
    self.navLabel.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入关键词" attributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}];
}


#pragma mark - UITableView DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_isHadBannar&&_bannarArray.count>0) {
        return 2;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            if (_bannarArray.count>0) {
                return 1;
            }
            else
            {
                return self.pageDataArr.count;
            }
        }
            break;
        case 1:
        {
            return self.pageDataArr.count;
        }
            break;
            
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.section) {
        case 0:
        {
            if (_bannarArray.count>0) {
                
                NewsFirstRecImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsFirstRecImageCell"];
                cell.VC = self;
                [self configureCell:cell atIndexPath:indexPath andCellType:0];
                return cell;
            }
            else
            {
                NewsListObj *obj = self.pageDataArr[indexPath.row];
                switch (obj.cellType) {
                    case KcellTypeNoImage: {
                        {
                            NewsNoImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsNoImageCell"];
                            [self configureCell:cell atIndexPath:indexPath andCellType:KcellTypeNoImage];
                            return cell;
                        }
                        break;
                    }
                    case KcellTypeSmallImage: {
                        {
                            NewsSmallImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsSmallImageCell"];
                            [self configureCell:cell atIndexPath:indexPath andCellType:KcellTypeSmallImage];
                            return cell;
                        }
                        break;
                    }
                    case KcellTypeBigImage: {
                        {
                            NewsBigImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsBigImageCell"];
                            [self configureCell:cell atIndexPath:indexPath andCellType:KcellTypeBigImage];
                            return cell;
                        }
                        break;
                    }
                }
            }
           
        }
            break;
        case 1:
        {
            NewsListObj *obj = self.pageDataArr[indexPath.row];
            switch (obj.cellType) {
                case KcellTypeNoImage: {
                    {
                        NewsNoImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsNoImageCell"];
                        [self configureCell:cell atIndexPath:indexPath andCellType:KcellTypeNoImage];
                        return cell;
                    }
                    break;
                }
                case KcellTypeSmallImage: {
                    {
                        NewsSmallImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsSmallImageCell"];
                        [self configureCell:cell atIndexPath:indexPath andCellType:KcellTypeSmallImage];
                        return cell;
                    }
                    break;
                }
                case KcellTypeBigImage: {
                    {
                        NewsBigImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsBigImageCell"];
                        [self configureCell:cell atIndexPath:indexPath andCellType:KcellTypeBigImage];
                        return cell;
                    }
                    break;
                }
            }
        }
            break;
            
        default:
            break;
    }
    
    return nil;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath andCellType:(KcellType)type
{
    switch (indexPath.section) {
        case 0:
        {
            if (_bannarArray.count>0) {
                
                cell.fd_enforceFrameLayout = YES ;
                NewsFirstRecImageCell *dataCell = (NewsFirstRecImageCell *)cell;
                [dataCell setCellData:_bannarArray];
            }
            else
            {
                 // Enable to use "-sizeThatFits:"
                switch (type) {
                    case KcellTypeNoImage: {
                        {
                            cell.fd_enforceFrameLayout = NO ;
                            NewsNoImageCell *dataCell = (NewsNoImageCell *)cell;
                            NewsListObj *obj = self.pageDataArr[indexPath.row];
                            [dataCell setCellData:obj];
                            
                        }
                        break;
                    }
                    case KcellTypeSmallImage: {
                        {
                            cell.fd_enforceFrameLayout = YES ;
                            NewsSmallImageCell *dataCell = (NewsSmallImageCell *)cell;
                            NewsListObj *obj = self.pageDataArr[indexPath.row];
                            [dataCell setCellData:obj];
                        }
                        break;
                    }
                    case KcellTypeBigImage: {
                        {
                            cell.fd_enforceFrameLayout = YES ;
                            NewsBigImageCell *dataCell = (NewsBigImageCell *)cell;
                            NewsListObj *obj = self.pageDataArr[indexPath.row];
                            [dataCell setCellData:obj];
                        }
                        break;
                    }
                }

            }
            
        }
            break;
        case 1:
        {
           
            switch (type) {
                case KcellTypeNoImage: {
                    {
                         cell.fd_enforceFrameLayout = NO ; // Enable to use "-sizeThatFits:"
                        NewsNoImageCell *dataCell = (NewsNoImageCell *)cell;
                        NewsListObj *obj = self.pageDataArr[indexPath.row];
                        [dataCell setCellData:obj];
                        
                    }
                    break;
                }
                case KcellTypeSmallImage: {
                    {
                        cell.fd_enforceFrameLayout = YES ;
                        NewsSmallImageCell *dataCell = (NewsSmallImageCell *)cell;
                        NewsListObj *obj = self.pageDataArr[indexPath.row];
                        [dataCell setCellData:obj];
                    }
                    break;
                }
                case KcellTypeBigImage: {
                    {
                        cell.fd_enforceFrameLayout = YES ;
                        NewsBigImageCell *dataCell = (NewsBigImageCell *)cell;
                        NewsListObj *obj = self.pageDataArr[indexPath.row];
                        [dataCell setCellData:obj];
                    }
                    break;
                }
            }
            
        }
            break;
            
        default:
            break;
    }
    
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            if (_bannarArray.count>0) {
                
                return [tableView fd_heightForCellWithIdentifier:@"NewsFirstRecImageCell" cacheByIndexPath:indexPath configuration:^(NewsFirstRecImageCell *cell) {
                    [self configureCell:cell atIndexPath:indexPath andCellType:0];
                }];
            }
            else
            {
                NewsListObj *obj = self.pageDataArr[indexPath.row];
                switch (obj.cellType) {
                    case KcellTypeNoImage: {
                        {
                            return [tableView fd_heightForCellWithIdentifier:@"NewsNoImageCell" cacheByIndexPath:indexPath configuration:^(NewsNoImageCell *cell) {
                                [self configureCell:cell atIndexPath:indexPath andCellType:obj.cellType];
                            }];
                        }
                        break;
                    }
                    case KcellTypeSmallImage: {
                        {
                            return [tableView fd_heightForCellWithIdentifier:@"NewsSmallImageCell" cacheByIndexPath:indexPath configuration:^(NewsSmallImageCell *cell) {
                                [self configureCell:cell atIndexPath:indexPath andCellType:obj.cellType];
                            }];
                        }
                        break;
                    }
                    case KcellTypeBigImage: {
                        {
                            return [tableView fd_heightForCellWithIdentifier:@"NewsBigImageCell" cacheByIndexPath:indexPath configuration:^(NewsBigImageCell *cell) {
                                [self configureCell:cell atIndexPath:indexPath andCellType:obj.cellType];
                            }];
                        }
                        break;
                    }
                }
            }
           
        }
            break;
        case 1:
        {
            NewsListObj *obj = self.pageDataArr[indexPath.row];
            switch (obj.cellType) {
                case KcellTypeNoImage: {
                    {
                        return [tableView fd_heightForCellWithIdentifier:@"NewsNoImageCell" cacheByIndexPath:indexPath configuration:^(NewsNoImageCell *cell) {
                            [self configureCell:cell atIndexPath:indexPath andCellType:obj.cellType];
                        }];
                    }
                    break;
                }
                case KcellTypeSmallImage: {
                    {
                        return [tableView fd_heightForCellWithIdentifier:@"NewsSmallImageCell" cacheByIndexPath:indexPath configuration:^(NewsSmallImageCell *cell) {
                            [self configureCell:cell atIndexPath:indexPath andCellType:obj.cellType];
                        }];
                    }
                    break;
                }
                case KcellTypeBigImage: {
                    {
                        return [tableView fd_heightForCellWithIdentifier:@"NewsBigImageCell" cacheByIndexPath:indexPath configuration:^(NewsBigImageCell *cell) {
                            [self configureCell:cell atIndexPath:indexPath andCellType:obj.cellType];
                        }];
                    }
                    break;
                }
            }
        }
            break;
            
        default:
            break;
    }
    
    return 0;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_bannarArray.count>0) {
        
        switch (indexPath.section) {
            case 0:
            {
                
            }
                break;
            case 1:
            {
                NewsListObj *obj = self.pageDataArr[indexPath.row];
                ZiXunDetailViewController *detail = [[ZiXunDetailViewController alloc] init];
                detail.titleForNav = @"资讯详情";
                if (obj.cellType == KcellTypeBigImage) {
                    detail.shareImageStr = obj.recoImage;
                }
                else if (obj.cellType == KcellTypeSmallImage)
                {
                    detail.shareImageStr = obj.coverImage;
                }
                detail.newsId = obj.internalBaseClassIdentifier;
                [self.navigationController pushViewController:detail animated:YES];
            }
                break;
            default:
                break;
        }
    }
    else
    {
        NewsListObj *obj = self.pageDataArr[indexPath.row];
        ZiXunDetailViewController *detail = [[ZiXunDetailViewController alloc] init];
        detail.titleForNav = @"资讯详情";
        if (obj.cellType == KcellTypeBigImage) {
            detail.shareImageStr = obj.recoImage;
        }
        else if (obj.cellType == KcellTypeSmallImage)
        {
            detail.shareImageStr = obj.coverImage;
        }
        detail.newsId = obj.internalBaseClassIdentifier;
        [self.navigationController pushViewController:detail animated:YES];
    }
    
    
    
   
}

# pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.navigationController.viewControllers.count >1) {
        return ;
    }
    if (_isHadBannar) {
        
        //[UIColor colorWithRed:255/255.0 green:175/255.0 blue:240/255.0 alpha:1];
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY > NAVBAR_CHANGE_POINT) {
            alpha = MIN(1, 1 - ((NAVBAR_CHANGE_POINT + 64 - offsetY) / 64));
            [self setMytitleViewType:KtitleViewTypeUnAlpha andAlpha:alpha];
//            if (alpha>0.5) {
//            }
//            else
//            {
//                [self setMytitleViewType:KtitleViewTypeNormal andAlpha:0.0];
//            }
        }
        else
        {
            [self setMytitleViewType:KtitleViewTypeNormal andAlpha:0.0];
        }    
    }
    else
    {
        [self setMytitleViewType:KtitleViewTypeUnAlpha andAlpha:1.0];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
